#! /usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

# Unfortunately, `flatc` doesn't output Rust 2018 conformant code which poses a
# problem when we want to embed it within a crate that requires it.
# The script here runs `flatc`, the flatbuffer compiler and then patches a bunch
# of code.
# Not proud of this...

import re
import subprocess

flatc_version = subprocess.check_output(["flatc", "--version"], text=True).strip()

subprocess.run(["flatc", "-o", "src/", "--rust", "src/graphqlschema.fbs"], check=True)

with open("src/graphqlschema_generated.rs") as f:
    content = f.read()

# add header

old_header = "// automatically generated by the FlatBuffers compiler, do not modify\n"
new_header = """/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * This file is generated, do not modify directly.
 *
 * Generated by:
 *   ./generate_flatbuffer.py
 *
 * Using:
 *   {}
 *
 * NOTE: The script requires `flatc` in the path which can be installed
 *       using `brew install flatbuffers` or similar.
 *
 * \x40generated
 */
""".format(flatc_version)

content = content.replace(old_header, new_header)

# add Clone to type, I think this was a manual add at some point
content = content.replace(
    "pub struct TypeArgs {", "#[derive(Copy, Clone)]\npub struct TypeArgs {"
)

# drop excessive empty lines
content = re.sub("\n{3,}", "\n\n", content)

with open("src/graphqlschema_generated.rs", "w") as f:
    f.write(content)
